#include<vector>
#include<iostream>
#include<map>
using namespace std;
map<int,int>pos;
vector<int>in,pre;

void lca(int inL,int inR,int preRoot,int a,int b){
    if(inL>inR) return;
    int inRoot=pos[pre[preRoot]],ina=pos[a],inb=pos[b];
    if((ina<inRoot && inb>inRoot)||(ina>inRoot && inb<inRoot)){
        printf("LCA of %d and %d is %d.\n",a,b,in[inRoot]);
    }
    else if(ina<inRoot && inb <inRoot){
        lca(inL,inRoot-1,preRoot+1,a,b);
    }
    else if(ina>inRoot && inb>inRoot){
        lca(inRoot+1,inR,preRoot+inRoot-inL+1,a,b);
    }
    else if (ina == inRoot)
            printf("%d is an ancestor of %d.\n", a, b);
    else if (inb == inRoot)
            printf("%d is an ancestor of %d.\n", b, a);
}
int main(){
    int M,N,a,b;
    scanf("%d %d",&M,&N);
    in.resize(N+1);pre.resize(N+1);
    for(int i=1;i<=N;i++){
        scanf("%d",&in[i]);
        pos[in[i]]=i;
    }
    for(int i=1;i<=N;i++){
        scanf("%d",&pre[i]);
    }
    for(int i=1;i<=M;i++){
        scanf("%d %d",&a,&b);
        if (pos[a] == 0 && pos[b] == 0)
            printf("ERROR: %d and %d are not found.\n", a, b);
        else if (pos[a] == 0 || pos[b] == 0)
            printf("ERROR: %d is not found.\n", pos[a] == 0 ? a : b);
        else
            lca(1, N, 1, a, b);
    }
}
